#include <iostream>
using namespace std;
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <netinet/in.h>
#include <ctype.h>
#include <pthread.h>
#define SERVER_PORT 8080

void*  handleClientInfo(void *arg)
{   
    pthread_detach(pthread_self());
    int connfd = *(int*)arg;
    int readBytes = 0;
    char buffer[1024] = {0};
    while(1)
    {
        readBytes = read(connfd,buffer,sizeof(buffer));
        if(readBytes < 0)
        {
            cout<<"readBytes < 0"<<endl;
            break;
        }
        else if(readBytes == 0)
        {
            cout<<"readBytes == 0"<<endl;
            break;
        }
        else
        {
            cout<<"buffer:"<<buffer<<endl;

            for(int idx = 0;idx < readBytes;idx++)
            {
                buffer[idx] = toupper(buffer[idx]);
            }
            // int i = 0;
            // while(buffer[i])
            // {   
            //     if(buffer[i] >= 'a'&&buffer[i] <= 'z')
            //     {
            //         buffer[i] = buffer[i] -('a'-'A');
            //     }
            //     i++;
            // }
            write(connfd,buffer,readBytes);
            }
    }
    //回收资源
    close(connfd);

    pthread_exit(NULL);
}
int main()
{
    //
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd == -1)
    {
        perror("socket error");
        _exit(-1);
    }

    int optVal = 1;
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&optVal,sizeof(optVal));
    if(ret != 0)
    {
        cout<<"端口复用失败"<<endl;
    }
    //绑定IP和端口
    struct sockaddr_in localAddress;
    memset(&localAddress,0,sizeof(localAddress));
    //地址族
    localAddress.sin_family = AF_INET;
    localAddress.sin_port = htons(SERVER_PORT);
    localAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    //绑定
    ret = bind(sockfd,reinterpret_cast<const sockaddr*>(&localAddress),sizeof(localAddress));

    //给监听的套接字设置监听
    ret = listen(sockfd,10);
    if(ret != 0)
    {
        perror("listen error:");
        _exit(-1);
    }

    int connfd = 0;
    int readBytes = 0;
    char buffer[1024] = {0};
    while(1)
    {   
        connfd = accept(sockfd,NULL,NULL);
        if(connfd == -1)
        {
            perror("accept error");
            _exit(-1);
        }

        //程序到达这个地方，就需要单独开辟线程去处理客户端的通信

        //
        pthread_t tid = 0;
        pthread_create(&tid,NULL,handleClientInfo,(void*)&connfd);
        if(ret != 0)
        {
            perror("thread create error:");
            _exit(-1);
        }
        
        sleep(1);
    }

    close(connfd);
    close(sockfd);
    cout<<"sockfd:"<<sockfd<<endl;
    cout<<"hello world!"<<endl;
    
    return 0;
}